<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\NewsController;
use App\Http\Controllers\Api\CategoryController;
use App\Http\Controllers\Api\Admin\NewsController as AdminNewsController;
use App\Http\Controllers\Api\Admin\CategoryController as AdminCategoryController;
use App\Http\Controllers\Api\Admin\UploadController;
use App\Http\Controllers\Api\Admin\UserController as AdminUserController;

// 公开接口
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

// 需要认证的接口
Route::middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::get('/user', [AuthController::class, 'user']);
    Route::put('/user', [AuthController::class, 'update']);
    Route::post('/user/upload', [AuthController::class, 'image']);

    // 新闻相关
    Route::get('/news', [NewsController::class, 'index']);
    Route::get('/news/realtime', [NewsController::class, 'realtime']);
    Route::get('/news/{id}', [NewsController::class, 'show']);
    Route::get('/news/{id}/comments', [NewsController::class, 'getComments']);
    Route::post('/news/{id}/comments', [NewsController::class, 'addComment']);

    // 分类相关
    Route::get('/categories', [CategoryController::class, 'index']);
    Route::get('/categories/{id}/news', [CategoryController::class, 'news']);
    Route::get('/categories/{id}/news', [CategoryController::class, 'news']);
});

// 管理员接口
Route::middleware(['auth:sanctum', 'admin'])->prefix('admin')->group(function () {
    Route::resource('news', AdminNewsController::class)->except(['create', 'edit']);
    Route::resource('categories', AdminCategoryController::class)->except(['create', 'edit']);
    Route::get('users', [AdminUserController::class, 'index']);
    Route::patch('users/{id}/role', [AdminUserController::class, 'updateRole']);
    Route::delete('users/{id}', [AdminUserController::class, 'destroy']);
    Route::post('/upload/image', [UploadController::class, 'image']);
    Route::get('/comments/count', function () {
        return [
            'total' => \App\Models\Comment::count() // 统计所有评论
        ];
    });
});